package com.channel.temperature.collect.ui.fragment

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.gyf.immersionbar.ktx.immersionBar
import com.hjy.bluetooth.HBluetooth
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.leon.lfilepickerlibrary.LFilePicker
import com.channel.temperature.collect.app.base.BaseFragment
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.DisplayUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.databinding.FragmentDataHandleBinding
import com.channel.temperature.collect.ui.activity.CachedDeviceListActivity
import com.channel.temperature.collect.ui.activity.OfflineDataActivity
import com.channel.temperature.collect.ui.activity.PdfActivity
import com.channel.temperature.collect.ui.viewmodel.DataHandleModel
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity


class DataHandleFragment : BaseFragment<DataHandleModel, FragmentDataHandleBinding>() {

    companion object {
        fun newInstance(): DataHandleFragment {
            val args = Bundle()
            val fragment = DataHandleFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBind.customToolbar.initBack("数据处理") {
            val messageDialog = MessageDialog(
                "提示", "退出程序？", "确定", "取消"
            ).setButtonOrientation(LinearLayout.HORIZONTAL)
            messageDialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                lifecycleScope.launch {
                    HBluetooth.getInstance().release()
                    activity?.finish()
                }
                false
            }
            if (this.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                messageDialog.setMaxWidth(resources.displayMetrics.widthPixels / 2)
            }
            messageDialog.show()
        }
    }

    /**
     * 懒加载 第一次获取视图的时候 触发
     */
    override fun lazyLoadData() {

    }

    override fun onRequestSuccess() {
        LiveDataEvent.showTitle.observe(this, Observer {
            if (it) {
                lifecycleScope.launch {
                    mBind.titleTv.visibility = View.VISIBLE
                    mBind.titleTv.text = "当前设备：" + mmkv.getString(
                        ValueKey.CURRENT_DEVICE_NAME, ""
                    ).toString()
                }

            }
        })
    }


    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mBind.readCacheData, mBind.readExcelFile, mBind.readPDFFile
        ) {
            when (it) {
                mBind.readCacheData -> {
                    toStartActivity(CachedDeviceListActivity::class.java)
                }

                mBind.readExcelFile -> {
                    val REQUESTCODE_FROM_ACTIVITY = 1000
                    val filtList: Array<String> = Array(1, { "" })
                    filtList[0] = "csv"
                    var startPath = mmkv.getString(ValueKey.START_PATH_KEY, "/storage/emulated/0")
                    LFilePicker().withActivity(requireActivity())
                        .withRequestCode(REQUESTCODE_FROM_ACTIVITY)
                        .withStartPath(startPath).withIsGreater(false)
                        .withFileSize((20000 * 1024).toLong()).withFileFilter(filtList)
                        .withMaxNum(1).withNotFoundBooks("请选择文件").start()
                }

                mBind.readPDFFile -> {
                    val REQUESTCODE_FROM_ACTIVITY = 1100
                    val filtList: Array<String> = Array(1, { "" })
                    filtList[0] = "pdf"
                    var startPath =
                        mmkv.getString(ValueKey.START_PATH_PDF_KEY, "/storage/emulated/0")
                    LFilePicker().withActivity(requireActivity())
                        .withRequestCode(REQUESTCODE_FROM_ACTIVITY)
                        .withStartPath(startPath).withIsGreater(false)
                        .withFileSize((20000 * 1024).toLong()).withFileFilter(filtList)
                        .withMaxNum(1).withNotFoundBooks("请选择文件").start()
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        immersionBar {
            titleBar(mBind.customToolbar)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == 1000) {
                val list: List<String>? = data?.getStringArrayListExtra("paths")
                var filePath = list?.get(0)
                var index = filePath?.lastIndexOf("/")
                mmkv.putString(ValueKey.START_PATH_KEY, index?.let { filePath?.substring(0, it) })
                var bundle = Bundle()
                bundle.putInt("dataMode", 2)
                bundle.putString("filePath", list?.get(0))
                mmkv.putBoolean(
                    "isLand",
                    DisplayUtil.getScreenHeight(activity) < DisplayUtil.getScreenWidth(activity)
                )
                bundle.putBoolean(
                    "isLand",
                    DisplayUtil.getScreenHeight(activity) < DisplayUtil.getScreenWidth(activity)
                )
                toStartActivity(OfflineDataActivity::class.java, bundle)
            } else if (requestCode == 1100) {
                val list: List<String>? = data?.getStringArrayListExtra("paths")
                var filePath = list?.get(0)
                var index = filePath?.lastIndexOf("/")
                mmkv.putString(
                    ValueKey.START_PATH_PDF_KEY,
                    index?.let { filePath?.substring(0, it) })
                var bundle = Bundle()
                bundle.putString("filePath", list?.get(0))
                toStartActivity(PdfActivity::class.java, bundle)
            }
        }
    }


}